package com.rainwen.shiro.security;

import com.rainwen.shiro.configuration.ShiroSettings;
import com.rainwen.shiro.entity.Role;
import com.rainwen.shiro.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.config.Ini;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.FactoryBean;

import java.util.List;
import java.util.Set;

/**
 * 借助spring {@link org.springframework.beans.factory.FactoryBean} 对apache shiro的premission进行动态创建
 * @author rain.wen
 * @date 2018/1/9.
 */
public class ChainDefinitionSectionMetaSource implements
        FactoryBean<Ini.Section> {

    private UserService userService;

    private ShiroSettings shiroSettings;

    private String username;


    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setShiroSettings(ShiroSettings shiroSettings) {
        this.shiroSettings = shiroSettings;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    // shiro默认的链接定义
    private String filterChainDefinitions;

    /**
     * 通过filterChainDefinitions对默认的链接过滤定义
     *
     * @param filterChainDefinitions
     *            默认的链接过滤定义
     */
    public void setFilterChainDefinitions(String filterChainDefinitions) {
        this.filterChainDefinitions = filterChainDefinitions;
    }

    @Override
    public Ini.Section getObject() throws BeansException {
        Ini ini = new Ini();
        // 加载默认的url
        ini.load(filterChainDefinitions);
        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);

        //循环数据库资源的url load from db
        //section.put("/user", "[]");

        // 循环数据库角色的url
        section.put("/user/**", "roles[user]");


        section.put("/**",section.remove("/**"));

        return section;
    }

    @Override
    public Class<?> getObjectType() {
        return Ini.Section.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
